package com.example.springbootvalidation.controller;

import com.example.springbootvalidation.result.Result;
import com.example.springbootvalidation.utils.BindingResultUtil;
import com.example.springbootvalidation.vo.TestVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@RestController
public class TestController {
    private final Logger logger= LoggerFactory.getLogger(TestController.class);

    /**
     * 返回所有不满足验证参数的提示
     * @param testVo
     * @param bindingResult
     * @return
     */
    @GetMapping("/test")
    public Result<TestVo> test(@Valid TestVo testVo , BindingResult bindingResult) {
        //判断是否有错，是否有不满足校验的参数
        if (bindingResult.hasErrors()) {
            //返回多个提示信息
            return BindingResultUtil.bindingResults(bindingResult);
        }
        logger.info("testVo={}"+testVo.toString());
        return Result.success(testVo);
    }

    /**
     * 只返回一个不满足验证参数的提示
     * @param testVo
     * @param bindingResult
     * @return
     */
    @GetMapping("/test1")
    public Result<TestVo> test1(@Valid TestVo testVo ,BindingResult bindingResult) {
        //判断是否有错，是否有不满足校验的参数
        if (bindingResult.hasErrors()) {
            //返回单个提示信息
            return BindingResultUtil.bindingResult(bindingResult);
        }
        logger.info("testVo={}"+testVo.toString());
        return Result.success(testVo);
    }

}
